<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .progress {
        border: solid;
        > div {
          height: 20px;
          background-color: blue;
          width: 0;
          color: white;
          text-align: center;
        }
      }
    </style>
  </head>
  <body>
    <div id="tip"></div>
    <form name="form">
      <input name="file" type="file" />
      <button type="button" id="upBtn">上传</button>
    </form>
    <div class="progress">
      <div id="progressBar"></div>
    </div>
    <script>
      function valid(file) {
        if (file === undefined) {
          tip.innerHTML = `请选择需要上传的文件`;
          return false;
        }
        //验证文件大小
        // byte K M G T
        const allowSize = 2; //2M
        if (file.size > 2 * 1024 * 1024) {
          tip.innerHTML = `文件大小不能超过${allowSize}M`;
          return false;
        }

        //限制扩展名
        const allowType = ["png", "jpg"];
        const ext = file.name.slice(file.name.lastIndexOf(".") + 1);

        if (allowType.includes(ext) === false) {
          tip.innerHTML = `文件后缀只能是 ${allowType}`;
          return false;
        }

        tip.innerHTML = "";
        return true;
      }

      document.form.file.onchange = function () {
        const file = form.file.files[0];
        valid(file);
      };

      upBtn.onclick = function () {
        const file = form.file.files[0];
        if (valid(file) === false) return;
        //---
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "http://127.0.0.1:8081/up");

        xhr.onload = function () {
          console.log(xhr.response);
          progressBar.innerHTML = "上传成功";
        };

        //上传进度事件
        xhr.upload.onprogress = function (e) {
          const r = (e.loaded / e.total) * 100 + "%";
          progressBar.style.width = r;
        };

        //----
        const fd = new FormData();
        fd.append("myfile", file);
        fd.append("name", "jack");
        fd.append("age", 20);
        xhr.send(fd);
      };
    </script>
  </body>
</html>
